package com.sgb.goods.widget;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.ColorUtils;
import com.sgb.goods.R;
import com.sgb.goods.api.GoodsCallBack;
import com.sgb.goods.api.GoodsNet;
import com.sgb.goods.entity.AdmixtureFaceEntity;
import com.sgb.goods.entity.AttributeViewEntity;
import com.sgb.goods.entity.BrandEntity;
import com.sgb.goods.entity.CommonStAttrEntity;
import com.sgb.goods.entity.ConcreteEntity;
import com.sgb.goods.entity.GoodsAttrEntity;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.entity.GoodsUnitEntity;
import com.sgb.goods.entity.MenuEntity1;
import com.sgb.goods.view.activity.inquiry.InquiryPublishingActivity;
import com.sgb.goods.view.adapter.publish.pop.BrandPopWindow;
import com.sgb.goods.view.adapter.publish.pop.GoodsTypePopWindow;
import com.sgb.goods.widget.pop.GoodsAttributeViewWindows;
import com.sgb.goods.widget.pop.StAttributeViewWindows;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.MToast;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author PC
 */
public class InquiryGoodsItemView extends LinearLayout implements ItemInputTextView.OnWholeItemClickListener {

    private LinearLayout downLayout;
    private TextView goodsTitleName;
    private TextView goodsTitleNum;
    private RelativeLayout ivDown;

    private LinearLayout llItemContainer;
    private ItemInputTextView goodsName;
    private ItemInputTextView goodsAttribute;
    private ItemInputTextView goodsBrand;
    private ItemInputTextView goodsUnit;
    private ItemInputTextView goodsAmount;
    private TextView tvDelete;
    private TextView goodsTitle;

    private RelativeLayout upLayout;

    private InquiryGoodsItemView.TransferClickEventListener transferClickEventListener;
    private int tag;
    private InquiryPublishingActivity mContext;

    /**
     * 商品分类选择弹窗
     */
    private GoodsTypePopWindow goodsNamePopWindow;

    /**
     * 商品属性选择弹窗
     */
    private GoodsAttributeViewWindows attributeViewWindows;

    /**
     * 品牌选择弹窗
     */
    private BrandPopWindow brandPopWindow;
    /**
     * 商砼属性选择弹窗
     */
    private StAttributeViewWindows stAttributeViewWindows;
    /**
     * 商品属性集合
     */
    private List<AttributeViewEntity> attributeViewEntityList;
    /**
     * 商砼属性集合
     */
    private List<CommonStAttrEntity> commonStAttrEntityList;

    /**
     * 商品分类列表
     */
    private List<MenuEntity1<MenuEntity1<MenuEntity1>>> goodsTypeEntityList;

    /**
     * 新三级类目id
     */
    private String goodsTypeCid3 = "";

    /**
     * 旧三级类目id(适用于属性)
     */
    private String lastAttributeCid3 = "";

    /**
     * 旧三级类目id(适用于品牌)
     */
    private String lastBrandCid3 = "";

    /**
     * 单位列表
     */
    private List<GoodsUnitEntity> unitEntityList;
    /**
     * 商砼type
     */
    private final static String GOODS_TYPE_ST = "商砼";
    /**
     * 选取商品是否为商砼
     */
    private boolean isChoiceST = false;
    /**
     * 单个商品sku实体类
     */
    private GoodsItemEntity goodsItem;

    /**
     * 单个商砼sku实体类
     */
    private ConcreteEntity concreteItem;

    /**
     * 品牌列表
     */
    private List<BrandEntity> brandEntityList;
    /**
     * 商品中心
     */
    private int goodsUnitPosition;

    /**
     * 弹框背景色
     */
    View grayView;

    /**
     * 点击view的回调
     */
    public interface TransferClickEventListener {
        /**
         * 点击事件回调
         *
         * @param viewId 组件id
         * @param tag    当前组件TAG
         */
        void transfer(int viewId, int tag);
    }

    public void setTransferClickEventListener(InquiryGoodsItemView.TransferClickEventListener listener) {
        this.transferClickEventListener = listener;
    }

    public InquiryGoodsItemView(Context context, View grayView) {
        super(context);
        this.mContext = (InquiryPublishingActivity) context;
        this.grayView = grayView;
        LayoutInflater.from(context).inflate(R.layout.goods_item_inquiry_view, this);
        initView();
        initListener();
        initPopWindow();
    }

    /**
     * 为view绑定model
     */
    public void initGoodsModel(Serializable serializable, boolean isCopy) {
        if (serializable == null) {
            this.goodsItem = new GoodsItemEntity();
            this.concreteItem = new ConcreteEntity();
        } else if (serializable instanceof ConcreteEntity) {
            loadData((ConcreteEntity) serializable, isCopy);
            this.goodsItem = new GoodsItemEntity();
        } else if (serializable instanceof GoodsItemEntity) {
            loadData((GoodsItemEntity) serializable, isCopy);
            this.concreteItem = new ConcreteEntity();
        }
    }

    private void loadData(ConcreteEntity concrete, boolean isCopy) {
        if (concrete == null) {
            this.concreteItem = new ConcreteEntity();
        } else {
            this.concreteItem = concrete;
            String goodName;
            if (TextUtils.isEmpty(concrete.getFcatName()) || TextUtils.isEmpty(concrete.getScatName()) || TextUtils.isEmpty(concrete.getTcatName())) {
                goodName = "";
            } else {
                goodName = concrete.getFcatName()
                        + "-" + concrete.getScatName()
                        + "-" + concrete.getTcatName();
            }
            setGoodsName(goodName);
            setAttribute(getConcreteAttribute(concrete));
            if (concrete.getNum() != null && concrete.getNum().endsWith(".0")) {
                setGoodsAmount(concrete.getNum().replace(".0", ""));
            } else {
                setGoodsAmount(concrete.getNum());
            }
            setBrandVisibility(false);
            setAttributeVisibility(true);
            setConcreteGoodsUnit("立方米");
            if (isCopy) {
                goodsName.setVisibility(VISIBLE);
                goodsAttribute.setVisibility(VISIBLE);
                goodsAmount.setVisibility(VISIBLE);
                goodsUnit.setVisibility(VISIBLE);
                goodsBrand.setVisibility(GONE);
            }
        }
        this.isChoiceST = true;
    }

    /***
     *设置商品属性信息
     * @param content 属性字符串值
     */
    private void setAttribute(String content) {
        this.goodsAttribute.setContent(content);
    }

    /***
     * 设置商品的采购量
     */
    private void setGoodsAmount(String amount) {
        this.goodsAmount.setContent(amount);
    }

    /****
     * 获取商砼属性值
     * @param concrete 商砼实体类
     */
    private String getConcreteAttribute(ConcreteEntity concrete) {
        StringBuilder stringBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(concrete.getStrongLevel())) {
            stringBuilder.append(concrete.getStrongLevel()).append(" ");
        }
        if (!TextUtils.isEmpty(concrete.getDeliveryMethod())) {
            stringBuilder.append("1".equals(concrete.getDeliveryMethod()) ? "一级配" : "二级配").append(" ");
        }
        if (!TextUtils.isEmpty(concrete.getConfig())) {
            stringBuilder.append("1".equals(concrete.getConfig()) ? "自卸" : "泵送").append(" ");
        }
        List<AdmixtureFaceEntity> admixtureFactList = concrete.getAdmixtureFactList();
        if (admixtureFactList != null && admixtureFactList.size() != 0) {
            for (AdmixtureFaceEntity admixtureFace : admixtureFactList) {
                if (!TextUtils.isEmpty(admixtureFace.getAdmixtureName())) {
                    stringBuilder.append(admixtureFace.getAdmixtureName()).append(" ");
                }
            }
        }
        return stringBuilder.toString();
    }

    /***
     * 普通商品
     * @param goodsItem 商品实体类
     */
    private void loadData(GoodsItemEntity goodsItem, boolean isCopy) {
        if (goodsItem == null) {
            this.goodsItem = new GoodsItemEntity();
        } else {
            this.goodsItem = goodsItem;
            String goodName;
            if (TextUtils.isEmpty(goodsItem.getFcatName()) || TextUtils.isEmpty(goodsItem.getScatName()) || TextUtils.isEmpty(goodsItem.getTcatName())) {
                goodName = "";
            } else {
                goodName = goodsItem.getFcatName()
                        + "-" + goodsItem.getScatName()
                        + "-" + goodsItem.getTcatName();
            }
            setGoodsName(goodName);
            String mAttribute = getGoodsItemAttribute(goodsItem);
            if ("".equals(mAttribute)) {
                setAttributeVisibility(false);
                goodsItem.setHaveAttribute(false);
            } else {
                setAttribute(mAttribute);
                goodsItem.setHaveAttribute(true);
            }
            if (goodsItem.getNum() != null && goodsItem.getNum().endsWith(".0")) {
                setGoodsAmount(goodsItem.getNum().replace(".0", ""));
            } else {
                setGoodsAmount(goodsItem.getNum());
            }
            setBrandName(goodsItem.getBrandName());
            setGoodsUnit(goodsItem.getUnit());
            if (isCopy) {
                goodsName.setVisibility(VISIBLE);
                if (goodsItem.isHaveAttribute()) {
                    goodsAttribute.setVisibility(VISIBLE);
                } else {
                    goodsAttribute.setVisibility(GONE);
                }
                goodsAmount.setVisibility(VISIBLE);
                goodsUnit.setVisibility(VISIBLE);
                goodsBrand.setVisibility(VISIBLE);
            }
        }
        this.isChoiceST = false;
    }

    private String getGoodsItemAttribute(GoodsItemEntity goodsItem) {
        List<GoodsAttrEntity> goodsItemAttrList = goodsItem.getAttrList();
        StringBuilder stringBuilder = new StringBuilder();
        if (goodsItemAttrList != null && goodsItemAttrList.size() != 0) {
            for (GoodsAttrEntity goodsAttr : goodsItemAttrList) {
                if (!TextUtils.isEmpty(goodsAttr.getParamValName())) {
                    stringBuilder.append(goodsAttr.getParamValName()).append(" ");
                }
            }
        }
        return stringBuilder.toString();
    }


    private void initListener() {
        tvDelete.setOnClickListener(this::OnWholeItemClick);
        upLayout.setOnClickListener(v -> {
            llItemContainer.setVisibility(GONE);
            downLayout.setVisibility(VISIBLE);
            String goodsName = this.goodsName.getContent();
            String goodsAttribute = this.goodsAttribute.getContent();
            String goodsAmount = this.goodsAmount.getContent();
            String goodsUnit = this.goodsUnit.getContent();
            setGoodsItemName(goodsName, goodsAttribute, goodsAmount, goodsUnit);
        });
        ivDown.setOnClickListener(v -> {
            llItemContainer.setVisibility(VISIBLE);
            downLayout.setVisibility(GONE);
        });
    }

    /****
     *设置单个商品的受说时标题名称
     * @param goodsName 品名
     * @param goodsAmount 采购量
     * @param goodsUnit 单位
     */
    @SuppressLint("SetTextI18n")
    private void setGoodsItemName(String goodsName, String goodsAttribute, String goodsAmount, String goodsUnit) {
        if (this.goodsAttribute.getVisibility() == VISIBLE) {
            if (TextUtils.isEmpty(goodsName) || TextUtils.isEmpty(goodsAttribute) || TextUtils.isEmpty(goodsAmount) || TextUtils.isEmpty(goodsUnit)) {
                goodsTitleName.setText("请填写商品信息");
                goodsTitleNum.setText("");
            } else {
                goodsTitleName.setText(goodsName);
                goodsTitleNum.setText(goodsAmount + goodsUnit);
                goodsTitleNum.setTextColor(Color.parseColor("#CC000000"));
            }
        } else {
            if (TextUtils.isEmpty(goodsName) || TextUtils.isEmpty(goodsAmount) || TextUtils.isEmpty(goodsUnit)) {
                goodsTitleName.setText("请填写商品信息");
                goodsTitleNum.setText("");
            } else {
                goodsTitleName.setText(goodsName);
                goodsTitleNum.setText(goodsAmount + goodsUnit);
                goodsTitleNum.setTextColor(Color.parseColor("#CC000000"));
            }
        }


//        if (goodsName == null || "".equals(goodsName)) {
//            goodsTitleName.setText("品名");
//            goodsTitleNum.setText("请选择商品");
//            goodsTitleNum.setTextColor(Color.parseColor("#C0C4CC"));
//        } else {
//            goodsTitleName.setText(goodsName);
//            goodsTitleNum.setText(goodsAmount + goodsUnit);
//            goodsTitleNum.setTextColor(Color.parseColor("#CC000000"));
//        }
    }

    private void initView() {
        downLayout = findViewById(R.id.goods_rl_item_title);
        downLayout.setVisibility(GONE);

        tvDelete = findViewById(R.id.goods_delete);
        tvDelete.setVisibility(GONE);

        goodsTitleName = findViewById(R.id.goods_tv_title_name);
        goodsTitleNum = findViewById(R.id.goods_tv_title_num);
        ivDown = findViewById(R.id.goods_rl_down);

        llItemContainer = findViewById(R.id.goods_ll_item_container);
        llItemContainer.setVisibility(VISIBLE);

        goodsName = findViewById(R.id.goods_item_name);
        goodsAttribute = findViewById(R.id.goods_item_attribute);
        goodsBrand = findViewById(R.id.goods_item_brand);
        goodsUnit = findViewById(R.id.goods_item_unit);
        goodsAmount = findViewById(R.id.goods_item_amount);
        goodsTitle = findViewById(R.id.goods_title);
        goodsAmount.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

        upLayout = findViewById(R.id.goods_rl_up);

        goodsName.setOnWholeItemClickListener(this);
        goodsAttribute.setOnWholeItemClickListener(this);
        goodsBrand.setOnWholeItemClickListener(this);
        goodsUnit.setOnWholeItemClickListener(this);
    }

    /**
     * 设置当前view的位置
     *
     * @param tag 当前view的位置
     */
    public void setCurrentViewTag(int tag) {
        this.tag = tag;
    }

    /**
     * 获取当前view的位置
     */
    public int getCurrentViewTag() {
        return this.tag;
    }

    @Override
    public void OnWholeItemClick(View view) {
        goodsAmount.clearFocus();
        if (view.getId() == R.id.goods_item_name) {
            if (goodsTypeEntityList != null) {
                showGoodsTypePop();
            } else {
                getGoodsCategory();
            }
        } else if (view.getId() == R.id.goods_item_attribute) {
            if (TextUtils.isEmpty(goodsName.getContent())) {
                MToast.showToast(mContext, "请先选择商品");
                return;
            }
            if (isChoiceST) {
                if (commonStAttrEntityList != null && commonStAttrEntityList.size() != 0) {
                    showStAttributePop(false);
                } else {
                    getStAttribute();
                }
            } else {
                if (TextUtils.isEmpty(goodsTypeCid3)) {
                    //复制过来得商品点击属性goodsTypeCid3为空
                    if (goodsItem != null && !"".equals(goodsItem.getTcategory())) {
                        getAttribute(goodsItem.getTcategory(), false);
                        goodsTypeCid3 = goodsItem.getTcategory();
                        lastAttributeCid3 = goodsItem.getTcategory();
                    }
                } else if (!goodsTypeCid3.equals(lastAttributeCid3)) {
                    getAttribute(goodsTypeCid3, false);
                    lastAttributeCid3 = goodsTypeCid3;
                } else {
                    if (attributeViewEntityList != null && attributeViewEntityList.size() > 0) {
                        showAttributePop(false);
                    } else {
                        getAttribute(goodsTypeCid3, false);
                        lastAttributeCid3 = goodsTypeCid3;
                    }
                }
            }
        } else if (view.getId() == R.id.goods_item_brand) {
            //复制过来得商品点击品牌goodsTypeCid3为空
            if (TextUtils.isEmpty(goodsTypeCid3)) {
                if (goodsItem != null && !"".equals(goodsItem.getTcategory())) {
                    goodsTypeCid3 = goodsItem.getTcategory();
                    lastBrandCid3 = goodsItem.getTcategory();
                    getBrand(goodsTypeCid3, "");
                }
            } else if (!goodsTypeCid3.equals(lastBrandCid3)) {
                getBrand(goodsTypeCid3, "");
                lastBrandCid3 = goodsTypeCid3;
            } else {
                if (brandEntityList != null) {
                    showBrandPop();
                } else {
                    getBrand(goodsTypeCid3, "");
                }
            }
        } else if (view.getId() == R.id.goods_item_unit) {
            if (!isChoiceST) {
                if (unitEntityList != null) {
                    goodsAmount.clearFocus();
                    showUnit();
                } else {
                    getUnitList("");
                }
            }
        } else {
            transferClickEventListener.transfer(view.getId(), getCurrentViewTag());
        }
    }

    /**
     * 商品个数的标题
     *
     * @param title 标题
     */
    public void setTitle(String title) {
        this.goodsTitle.setText(title);
    }

    /**
     * 设置商品的名字
     *
     * @param content 选框选取后商品的名字
     */
    public void setGoodsName(String content) {
        this.goodsName.setContent(content);
    }

    /**
     * 设置商品标题得颜色
     *
     * @param color 未填时
     */
    public void setGoodsNameColor(int color) {
        this.goodsName.getLabelNameView().setTextColor(ColorUtils.getColor(color));
    }

    /**
     * 选择的商品名字
     *
     * @return 商品名字
     */
    public String getGoodsName() {
        return this.goodsName.getContent();
    }

    /**
     * 设置UI商品的属性内容
     *
     * @param content 商品的属性
     */
    public void setGoodsAttribute(String content) {
        this.goodsAttribute.setContent(content);
    }


    /**
     * 设置属性标题得颜色
     *
     * @param color 未填时
     */
    public void setGoodsAttributeColor(int color) {
        this.goodsAttribute.getLabelNameView().setTextColor(ColorUtils.getColor(color));
    }

    /**
     * 设置商品的单位
     *
     * @param content 选框选取的品牌
     */
    public void setGoodsUnit(String content) {
        this.goodsUnit.setContent(content);
        goodsItem.setUnit(content);
    }

    /**
     * 设置单位标题得颜色
     *
     * @param color 未填时
     */
    public void setGoodsUnitColor(int color) {
        this.goodsUnit.getLabelNameView().setTextColor(ColorUtils.getColor(color));
    }

    /**
     * 设置商砼的单位
     *
     * @param content “立方米”
     */
    public void setConcreteGoodsUnit(String content) {
        this.goodsUnit.setContent(content);
        concreteItem.setUnit(content);
    }

    /**
     * 设置商品品牌
     *
     * @param content 选框选取的品牌
     */
    public void setBrandName(String content) {
        if (!TextUtils.isEmpty(content)) {
            this.goodsBrand.setContent(content);
            setBrandVisibility(true);
        } else {
            //没有品牌也显示出来
            setBrandVisibility(true);
        }

        goodsItem.setBrandName(content);
    }

    /**
     * 获取采购量
     *
     * @return 采购量
     */
    public String getGoodsAmount() {
        return this.goodsAmount.getContent();
    }

    /**
     * 设置采购量标题颜色
     *
     * @return 采购量颜色
     */
    public void setGoodsAmountColor(int color) {
        this.goodsAmount.getLabelNameView().setTextColor(ColorUtils.getColor(color));
    }

    /**
     * 获取商品实体类对象
     *
     * @return 商品实体类对象
     */
    public GoodsItemEntity getGoodsItem() {
        return goodsItem;
    }

    /**
     * 获取商砼实体类对象
     *
     * @return 商砼实体类对象
     */
    public ConcreteEntity getConcreteItem() {
        return concreteItem;
    }

    public void setDeleteVisibility(boolean isShow) {
        this.tvDelete.setVisibility(isShow ? VISIBLE : GONE);
    }

    /**
     * 设置属性集合
     *
     * @param attrList 属性集合实体类
     */
    public void setAttrList(List<GoodsAttrEntity> attrList) {
        goodsItem.setAttrList(attrList);
    }

    /**
     * 当前选择是否为商砼
     *
     * @param isChoiceST 是否为商砼
     */
    @Deprecated
    public void setIsSt(boolean isChoiceST) {
        this.isChoiceST = isChoiceST;
    }

    public boolean isChoiceST() {
        return this.isChoiceST;
    }

    /**
     * 设置品牌条目的可见性（商砼 无品牌属性）
     *
     * @param visibility 可见性
     */
    public void setBrandVisibility(boolean visibility) {
        goodsBrand.setVisibility(visibility ? View.VISIBLE : View.GONE);
    }

    /**
     * 设置商品属性条目的可见性
     *
     * @param visibility 可见性
     */
    public void setAttributeVisibility(boolean visibility) {
        goodsAttribute.setVisibility(visibility ? View.VISIBLE : View.GONE);
        if (!visibility) {
            setAttrList(new ArrayList<>());
        }
    }

    /**
     * 校验页面输入是否合规
     *
     * @return 是否合规
     */
    public void isInputValid() {
        if (TextUtils.isEmpty(goodsName.getContent())) {
            setGoodsNameColor(R.color.color_EF4033);
        } else {
            setGoodsNameColor(R.color.FF333333);
        }
        if (goodsAttribute.getVisibility() != View.GONE) {
            if (TextUtils.isEmpty(goodsAttribute.getContent())) {
                setGoodsAttributeColor(R.color.color_EF4033);
            } else {
                setGoodsAttributeColor(R.color.FF333333);
            }
        } else {
            setGoodsAttributeColor(R.color.FF333333);
        }
        if (TextUtils.isEmpty(goodsAmount.getContent())) {
            setGoodsAmountColor(R.color.color_EF4033);
        } else {
            setGoodsAmountColor(R.color.FF333333);
        }
        if (TextUtils.isEmpty(goodsUnit.getContent())) {
            setGoodsUnitColor(R.color.color_EF4033);
        } else {
            setGoodsUnitColor(R.color.FF333333);
        }
    }


    private void initPopWindow() {
        if (goodsNamePopWindow == null) {
            goodsNamePopWindow = new GoodsTypePopWindow(mContext);
        }
        goodsNamePopWindow.setBgView(grayView);
        goodsNamePopWindow.setOnResultClick((key1, key2, key3) -> {
            // 一级（左侧列表一级数据），obj1.id 代表 cid1
            MenuEntity1 obj1 = (MenuEntity1) key1;
            // 二级（右侧列表一级数据），obj2.id 代表 cid2
            MenuEntity1 obj2 = (MenuEntity1) key2;
            // 三级（右侧列表二级数据），obj3.id 代表 cid3
            MenuEntity1 obj3 = (MenuEntity1) key3;
            goodsTypeCid3 = obj3.id;
            resetGoodsAttribute();
            setGoodsName(obj1.name
                    + "-" + obj2.name
                    + "-" + obj3.name);
            if (!TextUtils.equals(GOODS_TYPE_ST, obj1.name)) {
                this.isChoiceST = false;
                getAttribute(goodsTypeCid3, true);
                setBrandVisibility(true);
                buildGoodsItem(obj1, obj2, obj3);
            } else {//商砼
                this.isChoiceST = true;
                buildConcrete(obj1, obj2, obj3);
                setBrandVisibility(false);
                setConcreteGoodsUnit("立方米");
                setAttributeVisibility(true);
            }
        });

        if (attributeViewWindows == null) {
            attributeViewWindows = new GoodsAttributeViewWindows(mContext);
        }
        attributeViewWindows.setBgView(grayView);
        attributeViewWindows.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        attributeViewWindows.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        attributeViewWindows.setOnResultClick((key1, key2, key3) -> buildAttrs(key1));

        if (stAttributeViewWindows == null) {
            stAttributeViewWindows = new StAttributeViewWindows(mContext);
        }
        stAttributeViewWindows.setBgView(grayView);
        stAttributeViewWindows.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        stAttributeViewWindows.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        stAttributeViewWindows.setOnResultClick((key1, key2, key3) -> {
            buildStAttrs(key1, key2);
        });

        if (brandPopWindow == null) {
            brandPopWindow = new BrandPopWindow(mContext);
        }
        brandPopWindow.setBgView(grayView);
        brandPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        brandPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        brandPopWindow.setOnResultClick((key1, key2, key3) -> {
            setBrandName((String) key2);
            goodsItem.setBrandId((String) key1);
        });
        brandPopWindow.inputTextInterface(value -> {
            hideInput();
            getBrand(goodsTypeCid3, value);
        });
    }

    /**
     * 重新选取商品后重置各个属性
     */
    private void resetGoodsAttribute() {
        goodsName.setContent("");
        goodsAttribute.setContent("");
        goodsBrand.setContent("");
        goodsAmount.setContent("");
        goodsUnit.setContent("");
    }

    /**
     * 构建商品基本属性
     */
    private void buildGoodsItem(MenuEntity1 menuEntity1, MenuEntity1 menuEntity2, MenuEntity1 menuEntity3) {
        goodsItem.setFcatName(menuEntity1.name);
        goodsItem.setFcategory(menuEntity1.id);
        goodsItem.setScatName(menuEntity2.name);
        goodsItem.setScategory(menuEntity2.id);
        goodsItem.setTcatName(menuEntity3.name);
        goodsItem.setTcategory(menuEntity3.id);
    }

    /**
     * 构建商砼基本属性
     */
    private void buildConcrete(MenuEntity1 menuEntity1, MenuEntity1 menuEntity2, MenuEntity1 menuEntity3) {
        concreteItem.setFcatName(menuEntity1.name);
        concreteItem.setFcategory(menuEntity1.id);
        concreteItem.setScatName(menuEntity2.name);
        concreteItem.setScategory(menuEntity2.id);
        concreteItem.setTcatName(menuEntity3.name);
        concreteItem.setTcategory(menuEntity3.id);
    }

    /**
     * 构建商品属性
     *
     * @param key1 商品属性
     */
    private void buildAttrs(Object key1) {
        List<GoodsAttrEntity> goodsAttrList = new ArrayList<>();
        StringBuilder stringBuffer = new StringBuilder();
        try {
            if (key1 instanceof String[]) {
                String[] checkedAttributes = (String[]) key1;
                if (checkedAttributes.length > 0) {
                    for (String attributeString : checkedAttributes) {
                        if (!TextUtils.isEmpty(attributeString)) {
                            String[] splitAttributes = attributeString.split("&");
                            GoodsAttrEntity goodsAttr = new GoodsAttrEntity();
                            goodsAttr.setParamId(splitAttributes[0]);
                            goodsAttr.setParamName(splitAttributes[1]);
                            goodsAttr.setParamValId(splitAttributes[2]);
                            goodsAttr.setParamValName(splitAttributes[3]);
                            goodsAttrList.add(goodsAttr);
                            stringBuffer.append(splitAttributes[3]).append(" ");
                        }
                    }
                    setAttrList(goodsAttrList);
                    goodsAttribute.setContent(stringBuffer.toString());
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 构建商砼属性
     *
     * @param key1 加强剂属性（多选）
     * @param key2 其他属性（单选）
     */
    private void buildStAttrs(Object key1, Object key2) {
        StringBuilder stringBuilder = new StringBuilder();
        if (key1 instanceof Map && key2 instanceof Map) {
            HashMap admixtureAttrMap = (HashMap) key1;
            HashMap otherAttrMap = (HashMap) key2;

            for (Map.Entry<String, CommonStAttrEntity.ChildListBean> otherAttr : (Iterable<Map.Entry<String, CommonStAttrEntity.ChildListBean>>) otherAttrMap.entrySet()) {
                CommonStAttrEntity.ChildListBean childListBean = otherAttr.getValue();
                buildConcreteAttribute(otherAttr.getKey(), null, childListBean, stringBuilder);
            }

            for (Map.Entry<String, List<CommonStAttrEntity.ChildListBean>> entry : (Iterable<Map.Entry<String, List<CommonStAttrEntity.ChildListBean>>>) admixtureAttrMap.entrySet()) {
                List<CommonStAttrEntity.ChildListBean> attributeList = entry.getValue();
                if (attributeList != null && attributeList.size() > 0) {
                    buildConcreteAttribute(entry.getKey(), attributeList, null, stringBuilder);
                }
            }
        }
    }

    /**
     * 构建商砼的属性信息
     *
     * @param key           属性标题
     * @param admixtureList 加强剂属性
     * @param otherAttr     其他属性
     * @param stringBuilder 拼接显示属性的builder
     */
    private void buildConcreteAttribute(String key, List<CommonStAttrEntity.ChildListBean> admixtureList, CommonStAttrEntity.ChildListBean otherAttr, StringBuilder stringBuilder) {
        if ("strength".equals(key)) {
            stringBuilder.append(otherAttr.getName()).append(" ");
            concreteItem.setStrongLevel(otherAttr.getName());
        }
        if ("config".equals(key)) {
            stringBuilder.append(otherAttr.getName()).append(" ");
            concreteItem.setConfig(TextUtils.equals(otherAttr.getName(), "一级配") ? "1" : "2");
        }
        if ("deliveryMethod".equals(key)) {
            stringBuilder.append(otherAttr.getName()).append(" ");
            concreteItem.setDeliveryMethod(TextUtils.equals(otherAttr.getName(), "自卸") ? "1" : "2");
        }
        if ("admixture".equals(key)) {
            List<AdmixtureFaceEntity> list = new ArrayList<>();
            for (CommonStAttrEntity.ChildListBean admixtureAttr : admixtureList) {
                if (admixtureAttr != null) {
                    AdmixtureFaceEntity admixtureFace = new AdmixtureFaceEntity();
                    admixtureFace.setAdmixtureName(admixtureAttr.getName());
                    admixtureFace.setSpec(String.valueOf(admixtureAttr.getSpec()));
                    if (TextUtils.isEmpty(admixtureAttr.getSpec())) {
                        stringBuilder.append(admixtureAttr.getName()).append(" ");
                    } else {
                        stringBuilder.append(admixtureAttr.getName()).append("-").append(admixtureAttr.getSpec()).append(" ");
                    }
                    list.add(admixtureFace);
                }
            }
            concreteItem.setAdmixtureFactList(list);
        }
        goodsAttribute.setContent(stringBuilder.toString());
    }

    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(INPUT_METHOD_SERVICE);
        View v = mContext.getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 显示商品类型
     */
    private void showGoodsTypePop() {
        if (!goodsNamePopWindow.isShowing()) {
            goodsNamePopWindow.showDownPopwindow(grayView, true);
        }
    }

    private void showGoodsTypePop(List<MenuEntity1<MenuEntity1<MenuEntity1>>> data) {
        this.goodsTypeEntityList = data;
        if (!goodsNamePopWindow.isShowing()) {
            goodsNamePopWindow.showDownPopwindow(grayView, true);
        }
        goodsNamePopWindow.setData(goodsTypeEntityList);
    }

    /**
     * 展示商品属性弹窗
     */
    private void showAttributePop(List<AttributeViewEntity> data) {
        this.attributeViewEntityList = data;
        showAttributePop(true);
    }


    private void showAttributePop(boolean isUpdate) {
        if (!attributeViewWindows.isShowing()) {
            attributeViewWindows.showDownPopwindow(grayView, true);
        }
        attributeViewWindows.setData(attributeViewEntityList, isUpdate);
    }


    /**
     * 显示商砼属性popWindow
     */
    private void showStAttributePop(boolean isUpdate) {
        if (!stAttributeViewWindows.isShowing()) {
            stAttributeViewWindows.showDownPopwindow(grayView, true);
        }
        stAttributeViewWindows.setData(commonStAttrEntityList, isUpdate);
    }

    public void showStAttributePop(List<CommonStAttrEntity> data) {
        this.commonStAttrEntityList = data;
        showStAttributePop(true);
    }

    /**
     * 显示商品品牌弹窗
     */
    public void showBrandPop(List<BrandEntity> data) {
        this.brandEntityList = data;
        showBrandPop();
    }

    private void showBrandPop() {
        if (!brandPopWindow.isShowing()) {
            brandPopWindow.showDownPopwindow(grayView, true);
        }
        brandPopWindow.setData(brandEntityList, goodsTypeCid3);
    }

    /**
     * 显示商品单位的弹窗
     */
    public void showUnit(List<GoodsUnitEntity> data) {
        this.unitEntityList = data;
        showUnit();
    }

    private void showUnit() {
        OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, (options1, options2, options3, v) -> {
            String content = unitEntityList.get(options1).getName();
            setGoodsUnit(content);
            goodsUnitPosition = options1;
        }).setLineSpacingMultiplier(2.0f)
                .setCancelColor(0xFF969696)
                .setTitleColor(0xFF969696)
                .setSubCalSize(15)
                .setTitleSize(15)
                .build();

        pickerView.setPicker(unitEntityList);
        pickerView.setSelectOptions(goodsUnitPosition);
        pickerView.setTitleText("选择单位");
        pickerView.show();
    }

    /**
     * 获取商品分类信息
     */
    public void getGoodsCategory() {
        GoodsNet.getInstance().getGoodsApi().goodsCategory().enqueue(new GoodsCallBack<BaseEntity<List<MenuEntity1<MenuEntity1<MenuEntity1>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MenuEntity1<MenuEntity1<MenuEntity1>>>> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                showGoodsTypePop(data.getData());
            }
        });
    }

    /**
     * 获取商品属性信息
     */
    public void getAttribute(String id, boolean isShowAttribute) {
        GoodsNet.getInstance().getGoodsApi().getAttribute(id).enqueue(new ICallBack<BaseEntity<List<AttributeViewEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AttributeViewEntity>> data) {
                List<AttributeViewEntity> dataList = data.getData();
                if (isShowAttribute && (dataList == null || dataList.size() == 0)) {
                    goodsItem.setHaveAttribute(false);
                    setAttributeVisibility(false);
                } else {
                    setAttributeVisibility(true);
                    goodsItem.setHaveAttribute(true);
                    if (isShowAttribute) {
                        return;
                    }
                    showAttributePop(data.getData());
                }
            }
        });
    }

    /**
     * 获取商砼属性信息
     */
    public void getStAttribute() {
        GoodsNet.getInstance().getGoodsApi().getStAttribute().enqueue(new GoodsCallBack<BaseEntity<List<CommonStAttrEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonStAttrEntity>> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                showStAttributePop(data.getData());
            }
        });
    }

    /**
     * 获取价格单位
     */
    public void getUnitList(String text) {
        GoodsNet.getInstance().getGoodsApi().unitList(text).enqueue(new GoodsCallBack<BaseEntity<List<GoodsUnitEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsUnitEntity>> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                showUnit(data.getData());
            }
        });
    }

    /**
     * 获取品牌信息
     */
    public void getBrand(String id, String text) {
        GoodsNet.getInstance().getGoodsApi().brandList(id, text).enqueue(new GoodsCallBack<BaseEntity<List<BrandEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<BrandEntity>> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                showBrandPop(data.getData());
            }
        });
    }


}
